package com.fanhang.samples.spring.session.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.session.ExpiringSession;
import org.springframework.session.MapSession;
import org.springframework.session.SessionRepository;

public class MemcachedSessionRepository implements SessionRepository<ExpiringSession> {

	protected Logger logger = LoggerFactory.getLogger(MemcachedSessionRepository.class);
	
	private MapSession session = new MapSession();
	
	public MemcachedSessionRepository() {
	}

	public ExpiringSession createSession() {
		logger.debug("createSession");
		return new MemcachedSession(session);
	}

	public void save(ExpiringSession session) {
		logger.debug("save: " + session);
	}

	public ExpiringSession getSession(String id) {
		logger.debug("getSession:" + id);
		return getSession(id, false);
	}

	public void delete(String id) {
		logger.debug("delete: " + id);
	}
	
	/**
	 *
	 * @param id the session id
	 * @param allowExpired
	 *            if true, will also include expired sessions that have not been
	 *            deleted. If false, will ensure expired sessions are not
	 *            returned.
	 * @return
	 */
	private MemcachedSession getSession(String id, boolean allowExpired) {
		MapSession loaded = new MapSession();
		loaded.setId(id);
		if(!allowExpired && loaded.isExpired()) {
			return null;
		}
		MemcachedSession result = new MemcachedSession(loaded);
		return result;
	}
}
